<?php

namespace app\common\model;

class Category extends BaseModel
{
    protected $append = ['image_url'];
    public function children()
    {
        return $this->hasMany(Category::class,'pid');
    }

    public function getImageUrlAttr($value,$data)
    {
        if (!$data['image']) return '';
        if (str_starts_with($data['image'], 'http')) {
            return $data['image'];
        } else {
            return request()->domain() . $data['image'];
        }
    }

    public static function getListWithUser($token = null)
    {
        $is_huo = "-1";
        $user_list = [];
        $category_list = Category::order("id desc")->field("id,title,image")->select();
        if ($token) {
            $user = User::where("token", $token)->find();
            if ($user) {
                $user_list = CategoryUser::where("user_id", $user['id'])
                    ->column('category_id');
            }
        }
        foreach ($category_list as &$category) {
            $category['is_huo'] = !empty($user_list) && in_array($category['id'], $user_list);
            $category['is_huo'] = $category['is_huo'] ? 1 : 0;
        }
        return $category_list;
    }
    
    // 获取用户已经激活的分类
    public static function getCategoryIdsByUser($token = null,$category_id = null)
    {
        if (!$token) return false;
        $user = User::where("token", $token)->find();
        if (!$user) return false;
        $list = CategoryUser::where("user_id", $user['id'])->column('category_id');
        if ($category_id) {
            return in_array($category_id, $list);
        } else {
            return $list;
        }
    }
}